package com.jht.bletool2java.activity.homepage.fragment.bledevice;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.permissions.OnPermission;
import com.hjq.permissions.XXPermissions;
import com.jht.bletool2java.BLEApplication;
import com.jht.bletool2java.R;
import com.jht.bletool2java.activity.homepage.fragment.bledevice.adapter.BleDeviceAdapter;
import com.jht.bletool2java.activity.homepage.fragment.bledevice.bean.BLEDevice;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.jetbrains.annotations.NotNull;

import java.util.List;

import it.gmariotti.recyclerview.adapter.SlideInBottomAnimatorAdapter;


public class BleDevicesFragment extends Fragment implements IBLEDevice.UI, BleDeviceAdapter.ScanCallback {
    private static final String TAG = "BleDevicesFragment";

    private SmartRefreshLayout mRefreshLayout;
    private RecyclerView mLvBleDevices;
    private BleDeviceAdapter bleDeviceAdapter;

    private BluetoothManager bluetoothManager;
    private IBLEDevice.Presenter presenter;
    private ScanUICallback scanUICallback;
    private Handler handler = new Handler();

    public BleDevicesFragment() {

    }

    public static BleDevicesFragment newInstance() {
        BleDevicesFragment fragment = new BleDevicesFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bluetoothManager = (BluetoothManager) (BLEApplication.getBLEApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE));
        presenter = new BleDevicesFragmentPresenter(this);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_ble_devices, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        mRefreshLayout = view.findViewById(R.id.refresh_layout);
        mLvBleDevices = view.findViewById(R.id.lv_ble_devices);
        mRefreshLayout.setEnableLoadMore(false);
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {

            @Override
            public void onRefresh(@NotNull RefreshLayout refreshlayout) {
                //判断蓝牙和定位是否开启
                if (isBTOpen() && isGPSOpen()) {
                    requestPermission();
                } else {
                    showToast(R.string.open_bt_location);
                }
                mRefreshLayout.finishRefresh(1000);
            }
        });

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        mLvBleDevices.setLayoutManager(linearLayoutManager);
        bleDeviceAdapter = new BleDeviceAdapter(getActivity());
        bleDeviceAdapter.setScanCallback(this);
        SlideInBottomAnimatorAdapter<BleDeviceAdapter.BleDeviceViewHolder> animatorAdapter = new SlideInBottomAnimatorAdapter<BleDeviceAdapter.BleDeviceViewHolder>(bleDeviceAdapter, mLvBleDevices);
        mLvBleDevices.setAdapter(bleDeviceAdapter);
    }

    private void requestPermission() {
        XXPermissions.with(getActivity())
                .permission(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
                .permission(Manifest.permission.RECORD_AUDIO)
                .request(new OnPermission() {
                    /**
                     * 1.蓝牙和定位是否开启：是-扫描设备，否-提醒用户打开蓝牙和定位
                     *
                     */
                    @Override
                    public void hasPermission(List<String> granted, boolean all) {
                        if (all) {
                            //权限全部授予,开始搜素蓝牙
                            Log.d(TAG, "hasPermission: 权限全部授予,开始搜素蓝牙 ");
                            presenter.startScanBle(bluetoothManager.getAdapter());
                        }
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean existNever) {
                        Log.i(TAG, "noPermission: " + existNever);
                        if (existNever) {
                            //存在永久拒绝的权限，解释原因，并跳转到权限授予界面
                        } else {
                            //解释为什么必须授予全部权限
                        }
                    }

                });
    }

    private boolean isBTOpen() {
        BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
        if (bluetoothAdapter == null) return false;
        return bluetoothAdapter.isEnabled();

    }

    private boolean isGPSOpen() {
        LocationManager locationManager = (LocationManager) (BLEApplication.getBLEApplicationContext()).getSystemService(Context.LOCATION_SERVICE);
        boolean gpsLocation = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean networkLocation = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        return gpsLocation || networkLocation;
    }

    @Override
    public void showToast(int msgId) {
        String msg = BLEApplication.getBLEApplicationContext().getResources().getString(msgId);
        Toast.makeText(BLEApplication.getBLEApplicationContext(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void addBleDevice(BLEDevice device) {
        bleDeviceAdapter.addDevice(device);
    }

    @Override
    public void stopBtScan() {
        presenter.stopScanBle(bluetoothManager.getAdapter());
        if (scanUICallback != null) {
            scanUICallback.stopBtScanUI();
        }
    }

    @Override
    public void stopBtScan(long delay) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "run: postDelayed scan time");
                presenter.stopScanBle(bluetoothManager.getAdapter());
                if (scanUICallback != null) {
                    scanUICallback.stopBtScanUI();
                }
            }
        }, delay);

    }

    @Override
    public void initScanUI(){
        if (scanUICallback != null) {
            scanUICallback.startBtScanUI();
        }
        bleDeviceAdapter.clear();
    }

    public void setScanUICallback(ScanUICallback scanUICallback) {
        this.scanUICallback = scanUICallback;
    }

    public interface ScanUICallback {
        void stopBtScanUI();

        void startBtScanUI();
    }

}